#include "tools.h"
#include <getch.h>
#include <string.h>
#include <assert.h>

unsigned int str_to_n(const char* str)
{
	const char* ret = str;
	unsigned int n = 0;
	int len = strlen(str);
	for(int i=0; i<len; i++)
	{
		n*=10;
		n+=(*ret++ -'0');
	}
	return n;
}

double str_to_double(const char* str)
{
	const char* ret = str;
	double n = 0.0, n2 = 0.0;
	int len = strlen(str);
	int point_index = str_chr(str,'.');
	for(int i=0; i<point_index; i++)
	{
		n *= 10;
		n += (*(ret+i) -'0');
	}
	for(int i=len-1; i>point_index; i--)
	{
		n2 += (*(ret+i) - '0');
		n2 /= 10;
	}
	n += n2;
	return n;
}

size_t str_chr(const char* str, const char ch)
{
	assert(NULL != str && ch);

	const char* ret = str;
	int len = strlen(str);
	for(int i=0; i<len; i++)
	{
		if(ch == *ret++) return i;
	}
	return len;
}

char get_cmd(char start,char end)
{
	assert(start <= end);

	puts("-------------------");
	printf("请输入指令：");
	for(;;)
	{
		char cmd = getch();
		if(start <= cmd && cmd <= end)
		{
			printf("%c\n",cmd);
			return cmd;
		}
	}
}

void print_sec(const char* msg,float sec)
{
	printf("\33[01;32m%s\33[00m\n",msg);
	usleep(1000000*sec);
}

void anykey_continue(void)
{
	stdin->_IO_read_ptr = stdin->_IO_read_end;
	puts("按任意键继续...");
	getch();
}

char* get_str(char* str,size_t size)
{
	assert(NULL!=str && size>1);

	// 计算fgets读取了多少个字符
	size_t len = strlen(fgets(str,size,stdin));

	// 如果最后一个字符是'\n'，则把它改为'\0'
	if('\n' == str[len-1])
		str[len-1] = '\0';
	else
		// 如果最后一个字符不是'\n'，则说明缓冲区中有垃圾数据，则需要清理输入缓冲区
		while('\n' != getchar());
	return str;
}

char* get_passwd(char* passwd,size_t size)
{
	int i = 0;
	while(i < size-1)
	{
		passwd[i] = getch();

		// 读取到退格键
		if(127 == passwd[i])
		{
			// 数组中有已输入密码
			if(i > 0)
			{
				// 删除一位密码
				i--;
				printf("\b \b");
			}
			continue;
		}
		
		i++;
		printf("*");
	}
	passwd[size-1] = '\0';
	printf("\n");
	return passwd;
}

bool yes_or_no(void)
{
	printf("是否确认此操作(y/n)?");
	for(;;)
	{
		char cmd = getch();
		if('y' == cmd || 'Y' == cmd || 'n' == cmd || 'N' == cmd)
		{
			printf("%c\n",cmd);
			return 'y'==cmd || 'Y'==cmd;
		}
	}
}

bool yes_or_no_notips(void)
{
	for(;;)
	{
		char cmd = getch();
		if('y' == cmd || 'Y' == cmd || 'n' == cmd || 'N' == cmd)
		{
			printf("%c\n",cmd);
			return 'y'==cmd || 'Y'==cmd;
		}
	}
}

// 通用的二进制保存数据
int save_data(void* base,size_t size,const char* path)
{
	assert(NULL!=base && NULL!=path);

	FILE* wfp = fopen(path,"w");
	if(NULL == wfp)
	{
		printf("无法打开文件，无法保存数据！\n");
		return 0;
	}

	int ret = fwrite(base,1,size,wfp);
	fclose(wfp);

	return ret;
}

// 通用的二进制加载数据
int load_data(void* base,size_t size,const char* path)
{
	assert(NULL!=base && NULL!=path);

	FILE* rfp = fopen(path,"r");
	if(NULL == rfp)
	{
		printf("无法打开文件，加载数据失败！\n");
		return 0;
	}

	int ret = fread(base,1,size,rfp);
	fclose(rfp);
	return ret;
}
